package com.lushuai.jiubeidanci.activity;

import android.content.Context;
import android.graphics.RenderEffect;
import android.graphics.Shader;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.lushuai.jiubeidanci.R;
import com.lushuai.jiubeidanci.model.Word;
import com.lushuai.jiubeidanci.model.Meaning;
import com.lushuai.jiubeidanci.util.WordDataUtil;

import java.util.List;
import java.util.Random;

public class WordLearnActivity extends AppCompatActivity {
    private TextView tvWord;
    private TextView tvPhonetic;
    private ImageButton btnBack;
    private ImageButton btnRefresh;
    private ImageButton btnStar;
    private ImageButton btnMore;
    private ImageButton btnPronunciation;
    private Button btnShowAnswer;
    private LinearLayout[] optionLayouts = new LinearLayout[4];
    private boolean isStarred = false;
    private int correctOptionIndex = -1;
    private boolean isAnswerShown = false;
    private List<Word> words;
    private int currentWordIndex = 0;
    private TextView tvProgress;
    private int correctCount = 0;
    private static final int TOTAL_WORDS = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_learn);

        // 加载单词数据
        words = WordDataUtil.loadWords(this);
        currentWordIndex = 0; // 确保从第一个单词开始
        correctCount = 0; // 初始化正确计数
        
        initViews();
        setupClickListeners();
        setupBlurEffect();
        loadWordData();
    }

    private void initViews() {
        tvWord = findViewById(R.id.tv_word);
        tvPhonetic = findViewById(R.id.tv_phonetic);
        btnBack = findViewById(R.id.btn_back);
        btnRefresh = findViewById(R.id.btn_refresh);
        btnStar = findViewById(R.id.btn_star);
        btnMore = findViewById(R.id.btn_more);
        btnPronunciation = findViewById(R.id.btn_pronunciation);
        btnShowAnswer = findViewById(R.id.btn_show_answer);

        // 初始化选项布局
        optionLayouts[0] = findViewById(R.id.option_1);
        optionLayouts[1] = findViewById(R.id.option_2);
        optionLayouts[2] = findViewById(R.id.option_3);
        optionLayouts[3] = findViewById(R.id.option_4);

        tvProgress = findViewById(R.id.tv_progress);
        updateProgress();
    }

    private void setupClickListeners() {
        btnBack.setOnClickListener(v -> finish());

        btnRefresh.setOnClickListener(v -> loadWordData());

        btnStar.setOnClickListener(v -> {
            isStarred = !isStarred;
            btnStar.setImageResource(isStarred ? R.drawable.ic_star_filled : R.drawable.ic_star_border);
        });

        btnPronunciation.setOnClickListener(v -> {
            // TODO: 播放单词发音
        });

        // 设置选项点击事件
        for (int i = 0; i < optionLayouts.length; i++) {
            final int index = i;
            optionLayouts[i].setOnClickListener(v -> onOptionClick(index));
        }

        btnShowAnswer.setOnClickListener(v -> {
            if (!isAnswerShown) {
                // 显示正确答案
                for (int i = 0; i < optionLayouts.length; i++) {
                    LinearLayout layout = optionLayouts[i];
                    TextView meaningTextView = (TextView) layout.getChildAt(1);
                    String meaning = meaningTextView.getText().toString();
                    
                    // 检查是否是正确答案
                    if (meaning.equals(words.get(currentWordIndex).getCorrectAnswer())) {
                        layout.setSelected(true);
                    } else {
                        layout.setSelected(false);
                    }
                }
                isAnswerShown = true;
                btnShowAnswer.setText("继续");
            } else {
                // 继续下一个单词
                currentWordIndex++;
                if (currentWordIndex >= TOTAL_WORDS) {
                    showResultDialog();
                } else {
                    loadWordData();
                }
            }
        });
    }

    private void onOptionClick(int index) {
        if (isAnswerShown) return; // 如果已经显示答案，不再响应点击

        // 清除其他选项的选中状态
        for (LinearLayout layout : optionLayouts) {
            layout.setSelected(false);
        }
        
        // 设置当前选项为选中状态
        optionLayouts[index].setSelected(true);

        // 获取选中的答案文本
        TextView selectedAnswerView = (TextView) ((LinearLayout) optionLayouts[index]).getChildAt(1);
        String selectedAnswer = selectedAnswerView.getText().toString();

        // 检查答案
        Word currentWord = words.get(currentWordIndex);
        if (selectedAnswer.equals(currentWord.getCorrectAnswer())) {
            handleCorrectAnswer(index);
        } else {
            handleWrongAnswer(index);
        }
    }

    private void handleCorrectAnswer(int index) {
        // 显示正确动画
        optionLayouts[index].animate()
            .scaleX(1.1f)
            .scaleY(1.1f)
            .setDuration(200)
            .withEndAction(() -> {
                optionLayouts[index].animate()
                    .scaleX(1f)
                    .scaleY(1f)
                    .setDuration(200)
                    .withEndAction(this::moveToNextWord)
                    .start();
            })
            .start();

        correctCount++;
    }

    private void handleWrongAnswer(int index) {
        // 震动反馈
        vibrate();

        // 显示错误动画
        optionLayouts[index].animate()
            .translationX(50)
            .setDuration(100)
            .withEndAction(() -> {
                optionLayouts[index].animate()
                    .translationX(-50)
                    .setDuration(100)
                    .withEndAction(() -> {
                        optionLayouts[index].animate()
                            .translationX(0)
                            .setDuration(100)
                            .start();
                    })
                    .start();
            })
            .start();
    }

    private void moveToNextWord() {
        currentWordIndex++;
        if (currentWordIndex >= TOTAL_WORDS) {
            showResultDialog();
        } else {
            new Handler().postDelayed(this::loadWordData, 500);
        }
    }

    private void showResultDialog() {
        new AlertDialog.Builder(this)
            .setTitle("学习完成")
            .setMessage(String.format("本次学习完成！\n正确率：%d%%", (correctCount * 100 / TOTAL_WORDS)))
            .setPositiveButton("继续学习", (dialog, which) -> {
                currentWordIndex = 0;
                correctCount = 0;
                loadWordData();
            })
            .setNegativeButton("返回", (dialog, which) -> finish())
            .setCancelable(false)
            .show();
    }

    private void playSound(int soundResId) {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, soundResId);
        mediaPlayer.setOnCompletionListener(MediaPlayer::release);
        mediaPlayer.start();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null && vibrator.hasVibrator()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
            } else {
                vibrator.vibrate(100);
            }
        }
    }

    private void loadWordData() {
        if (words.isEmpty()) return;

        // 更新进度显示
        updateProgress();

        // 重置答案显示状态
        isAnswerShown = false;
        btnShowAnswer.setText("看答案");

        Word currentWord = words.get(currentWordIndex);
        
        // 重置选项状态
        for (LinearLayout layout : optionLayouts) {
            layout.setSelected(false);
        }

        // 加载单词数据
        tvWord.setText(currentWord.getWord());
        tvPhonetic.setText(currentWord.getPhonetic());

        List<Meaning> meanings = currentWord.getMeanings();
        String[] options = new String[meanings.size()];
        correctOptionIndex = -1;
        
        // 设置选项，并记录正确答案的位置
        for (int i = 0; i < meanings.size(); i++) {
            options[i] = meanings.get(i).getDefinition();
            if (meanings.get(i).getDefinition().equals(currentWord.getCorrectAnswer())) {
                correctOptionIndex = i;
            }
        }

        // 随机打乱选项顺序
        shuffleOptions(options);

        // 设置选项文本和词性
        for (int i = 0; i < optionLayouts.length; i++) {
            LinearLayout optionLayout = optionLayouts[i];
            TextView typeTextView = (TextView) optionLayout.getChildAt(0);
            TextView meaningTextView = (TextView) optionLayout.getChildAt(1);
            
            typeTextView.setText(meanings.get(i).getType());
            meaningTextView.setText(options[i]);
        }
    }

    private void shuffleOptions(String[] options) {
        Random random = new Random();
        for (int i = options.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            String temp = options[i];
            options[i] = options[j];
            options[j] = temp;
            if (j == correctOptionIndex) {
                correctOptionIndex = i;
            } else if (i == correctOptionIndex) {
                correctOptionIndex = j;
            }
        }
    }

    private void setupBlurEffect() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            RenderEffect blurEffect = RenderEffect.createBlurEffect(
                    20f,
                    20f,
                    Shader.TileMode.CLAMP
            );

            // 只对背景应用模糊效果
            findViewById(R.id.blur_background_1).setRenderEffect(blurEffect);
            findViewById(R.id.blur_background_2).setRenderEffect(blurEffect);
            findViewById(R.id.blur_background_3).setRenderEffect(blurEffect);
            findViewById(R.id.blur_background_4).setRenderEffect(blurEffect);
        }
    }

    private void updateProgress() {
        if (tvProgress != null) {
            tvProgress.setText(String.format("%d/%d", currentWordIndex + 1, TOTAL_WORDS));
        }
    }
} 